package com.topsoft.micro.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.topsoft.micro.config.handler.MyAuthenticationFailureHandler;
import com.topsoft.micro.config.handler.MyOwnSavedRequestAwareAuthenticationSuccessHandler;
import com.topsoft.micro.security.MyUserDetailsService;

/**
 * 
 * @author guokaige
 *
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyUserDetailsService myUserDetailsService;
    
    @Autowired
    MyOwnSavedRequestAwareAuthenticationSuccessHandler   myOwnSavedRequestAwareAuthenticationSuccessHandler;
    
    @Autowired
    MyAuthenticationFailureHandler  myAuthenticationFailureHandler;

     

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	
		 //跨站请求伪造
    	http.csrf().disable();
    	 //解决iframe问题
    	http.headers().frameOptions().disable();
    	
    	
        http.authorizeRequests()
                .antMatchers("/oauth/**","/login/**", "/logout").permitAll()
                .anyRequest().authenticated()   // 其他地址的访问均需验证权限
                .and()
                .formLogin()
                .loginPage("/login")
	            //指定登陆action 的 url
	            .loginProcessingUrl("/authentication/form")  
	            //登录成功处理
	            .successHandler(myOwnSavedRequestAwareAuthenticationSuccessHandler)  
	            //登录失败处理
	            .failureHandler(myAuthenticationFailureHandler);


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
        //.passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
    	
        return super.authenticationManager();
    }

//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
//    }

}
